package com.yi.wood.web.ctrl;

import com.yi.wood.base.Result;
import com.yi.wood.base.ResultCodeEnum;
import com.yi.wood.service.po.AppUserCachePo;
import com.yi.wood.service.po.CachePo;
import com.yi.wood.service.po.UserCachePo;
import com.yi.wood.utils.StringTokenUtil;
import com.yi.wood.web.ctrl.dto.PageVo;
import com.yi.wood.web.util.UserCacheUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author moyi
 */
@Validated
public abstract class BaseCtrl {

    @Autowired
    protected HttpServletRequest request;

    @Autowired
    private UserCacheUtil userCacheUtil;

    private Map<Object,Object> resultMap;

    protected Result success(){
        return new Result(ResultCodeEnum.SUCCESS,null);
    }

    protected Result success(Object data){
        return new Result(ResultCodeEnum.SUCCESS,data);
    }

    protected Result success(Page<?> page){
        PageVo pageVo = new PageVo(page.getContent(), (page.getNumber()+1), page.getSize(), page.getTotalElements());
        return new Result(ResultCodeEnum.SUCCESS, pageVo);
    }

    protected Result exception(ResultCodeEnum resultCodeEnum){
        return new Result(resultCodeEnum,null);
    }

    protected Map<Object,Object> result(){
        int defaultSize = 10;
        return result(defaultSize);
    }

    protected Map<Object,Object> result(int size){
        if (resultMap == null){
            resultMap = new HashMap<>(size);
        }
        return resultMap;
    }

    protected Map<Object,Object> put(Object key, Object val){
        result().put(key,val);
        return resultMap;
    }

    private String getToken(){
        return request.getHeader("Wood-Token");
    }

    CachePo getUserByToken(){
        Object obj = request.getSession().getAttribute("userInfo");
        if (!Objects.isNull(obj) && obj instanceof CachePo){
            return (CachePo) obj;
        }
        String token = getToken();
        if (!StringUtils.isEmpty(token)){
            return userCacheUtil.getUserByCache(StringTokenUtil.unPrefix(token));
        }
        return null;
    }
}
